package uiTest;

import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.EventObject;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
 
public class TableTest extends JFrame
{
	private static final String[] colVals = {
		"A",
		"B",
		"C",
		"D"
	};
	
	JTable table;
	
	private class TestEditor extends DefaultCellEditor
	{
		public TestEditor(JComboBox comp)
		{
			super(comp);
		}
		
		@Override
		public boolean isCellEditable(EventObject e)
		{
			// Reject any editing that wasn't started programmatically.
			return e == null;
		}
	}
	
	public TableTest()
	{
		DefaultTableModel tableModel = new DefaultTableModel(
				new String[][]{colVals},
				new String[]{"1", "2", "3", "4"});
		
		table = new JTable(tableModel);
		
		DefaultCellEditor editor = new TestEditor(
				new JComboBox(colVals));
		
		TableColumnModel colModel = table.getColumnModel();
		
		for (int i=0; i<colModel.getColumnCount(); i++)
		{	
			TableColumn col = colModel.getColumn(i);
			col.setCellEditor(editor);
			col.setPreferredWidth(20);
		}
		
		table.addMouseListener(new MouseAdapter(){
			@Override
			public void mouseClicked(MouseEvent e)
			{
				Point p = e.getPoint();
				int r = table.rowAtPoint(p);
				int c = table.columnAtPoint(p);
				
				if (e.getButton() == MouseEvent.BUTTON1 && 
						e.getClickCount() == 2)
				{
					TableColumn col = table.getColumnModel().getColumn(c);
					col.setPreferredWidth(60);
					table.editCellAt(r, c);
				}
			}
		});
		
		JPanel p = new JPanel();
		p.add(table);
		setContentPane(p);
		
		table.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				Point p = e.getPoint();
				final int r = table.rowAtPoint(p);
				final int c = table.columnAtPoint(p);
		 
				if (e.getButton() == MouseEvent.BUTTON1 &&
						e.getClickCount() == 2)
				{
					TableColumn col = table.getColumnModel().getColumn(c);
					col.setPreferredWidth(60);
		 
					SwingUtilities.invokeLater(new Runnable()
					{
						public void run()
						{
							table.editCellAt(r, c);
						}
					});
				}
			}
		});
		
	}
	
	public static void main(String[] args)
	{
		JFrame frame = new TableTest();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(300, 100);
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
	}
}